package com.spring.framgent;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.spring.activity.AceActivity;
import com.spring.activity.LeaveActivity;
import com.spring.activity.LoginActivity;
import com.spring.activity.MyAccountActivity;
import com.spring.activity.MyBillActivity;
import com.spring.activity.QueryKQInfoActivity;
import com.spring.activity.ScanPayActivity;
import com.spring.activity.UpdatePassActivity;
import com.spring.adapter.ImageAdapter;
import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.model.ImageData;
import com.spring.model.QueryVersion;
import com.spring.model.ReturnImageList;
import com.spring.tool.App;
import com.spring.util.Constant;
import com.spring.util.ImageBetter;
import com.spring.util.ImageOptions;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import zxing.android.CaptureActivity;

/**
 * 首页界面
 *
 * @author Administrator
 */
public class Index_Fragment extends Fragment implements OnClickListener,
        OnPageChangeListener {
    private final static int SCANNIN_GREQUEST_TWO = 2;
    private final static int SCANNIN_GREQUEST_ONE = 1;
    private final static int SCANNIN_GREQUEST_Three = 3;
    private ViewPager vp;
    private ViewPagerAdapter vpAdapter;
    private List<View> views;
    private int width;
    private int height;
    private DisplayImageOptions options;
    private TextView btnloading;
    private RelativeLayout relativeLayout;
    private ImageBetter imageBetter;
    public MyHandler myHandler;
    private String succes;
    // 引导图片资源
    private static final int[] pics = {0, 1, 2, 3, 4};
    private static final String BASE_URL = "http://10.10.8.249:8072/WebService.asmx?op=";
    // 底部小店图片
    private ImageView[] dots;

    // 记录当前选中位置
    private int currentIndex;
    private View view;
    LinearLayout.LayoutParams mParams = null;
    private List<ImageView> listviews;
    private ViewFlow viewFlow;
    public String[] urls;

    String username = "";
    String logintype = null;
    RestClient restClient = null;
    private ImageView logoimage;
    String Imageurl = null;
    List<ImageData> list = null;
    ReturnImageList imagelist;

    private int currentV = 0, newV = 0;
    private JSONObject jo_v;
    private String newVContent = "";
    QueryVersion contactData;
    private ProgressBar pb;
    private TextView tv;
    public static int loading_process;
    private SharedPreferences userInfo;
    private String userName, type;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (App.getInstance().isLogin()) {
            userInfo = getActivity().getSharedPreferences(
                    "user_info", 0);
            username = userInfo.getString("username", "");
            logintype = userInfo.getString("logintype", "");

        }
        initImageLoader(getActivity());
        imageBetter = ImageBetter.getInstance();
        options = ImageOptions.getLoadImageOptions();
        myHandler = new MyHandler();
        restClient = new RestClient(getActivity());

        //		boolean islianwang = new Constant().isConnect(getActivity());
        //		if (islianwang) {
        //			SendHttpData();
        //		} else {
        //			Toast.makeText(getActivity(), "请检查手机是否联网！", 2).show();
        //		}


    }

    private void showAd() {
        urls = new String[]{"http://i5.tietuku.com/5776f159ee9a3c60.png",
                "http://i5.tietuku.com/702a21bfa5a2dab3.png",
                "http://i12.tietuku.com/5a9a6f4690940b3b.jpg",
                "http://i12.tietuku.com/315cc4d2d029072d.jpg",
                "http://i5.tietuku.com/8eec1293cbe79d52.png"
        };
        if (urls != null && urls.length > 0) {
            if (viewFlow != null) {
                viewFlow.setAdapter(new ImageAdapter(getActivity(),
                        urls, imagelist));
                viewFlow.setmSideBuffer(pics.length); // 实际图片张数，
                // 我的ImageAdapter实际图片张数为3

                CircleFlowIndicator indic = (CircleFlowIndicator) view
                        .findViewById(R.id.viewflowindic);
                viewFlow.setFlowIndicator(indic);
                viewFlow.setTimeSpan(2000);
                viewFlow.setSelection(3 * 1000); // 设置初始位置
                viewFlow.startAutoFlowTimer(); // 启动自动播放
            }

        }
    }


    public boolean isConnect(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        showActionbar();
    }

    public static void initImageLoader(Context context) {

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.index, container, false);

        btnloading = (TextView) view.findViewById(R.id.btnloading);
        logoimage = (ImageView) view.findViewById(R.id.logoimage);
        logoimage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (list != null && list.size() > 0) {
                    String linkUrl = list.get(0).getLinkUrl();
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(linkUrl);
                    intent.setData(content_url);
                    getActivity().startActivity(intent);
                }
            }
        });
        System.out.println(App.getInstance().isLogin());
        showActionbar();
        btnloading.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!App.getInstance().isLogin()) {
                    gotoLoginView();
                } else {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("提示")
                            .setMessage("你确定要退出系统吗？")
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method
                                            // stub
                                            btnloading.setText("登录");
                                            SharedPreferences userInfo = getActivity().getSharedPreferences(
                                                    "user_info", 0);
                                            userInfo.edit().putBoolean("login", false).commit();
                                        }
                                    })
                            .setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method
                                            // stub

                                        }
                                    }).show();
                }
            }
        });

        Button button = (Button) view.findViewById(R.id.btnshouye_yhzh);// 银行账户
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getActivity(), "实时转账：系统未接入外网，无法与银行通信", Toast.LENGTH_SHORT).show();
            }
        });

        Button btnmybill = (Button) view.findViewById(R.id.btnshouye_wdzd);// 我的账单
        btnmybill.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), MyBillActivity.class);
                    startActivity(intent);
                }

            }
        });

        Button btnremove = (Button) view.findViewById(R.id.btnshouye_wdzh);// 我的账户
        btnremove.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), MyAccountActivity.class);
                    startActivity(intent);
                }
            }
        });
        //

        Button btnshouzhi = (Button) view.findViewById(R.id.btnshouye_szfx);// 解挂
        btnshouzhi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("提示")
                            .setMessage("你确定要解挂吗？")
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method
                                            // stub
                                            boolean islianwang = new Constant()
                                                    .isConnect(getActivity());
                                            if (islianwang) {
                                                SendHttpData sendhttpdata = new SendHttpData(
                                                        App.getInstance().url
                                                                + "/UnLockCard",
                                                        "1");
                                                sendhttpdata.run();
                                            } else {
                                                Toast.makeText(
                                                        getActivity(),
                                                        "请检查手机是否联网！", Toast.LENGTH_SHORT)
                                                        .show();
                                            }

                                        }
                                    })
                            .setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method
                                            // stub

                                        }
                                    }).show();


                }
            }
        });


        Button btnidentity = (Button) view
                .findViewById(R.id.btnshouye_updatepass);// 修改密码
        btnidentity.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), UpdatePassActivity.class);
                    startActivity(intent);
                }
            }
        });

        Button btnreport = (Button) view.findViewById(R.id.btnshouye_sfrz);// 身份证信息查询
        btnreport.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), QueryKQInfoActivity.class);
                    startActivity(intent);
                }
            }
        });

        Button btnrecharge = (Button) view.findViewById(R.id.btnshouye_zzgs);// 自助挂失
        btnrecharge.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("提示")
                            .setMessage("你确定要挂失吗？")
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method
                                            // stub
                                            boolean islianwang = new Constant()
                                                    .isConnect(getActivity());
                                            if (islianwang) {
                                                SendHttpData sendhttpdata = new SendHttpData(
                                                        App.getInstance().url
                                                                + "/LockCard",
                                                        "2");
                                                sendhttpdata.run();
                                            } else {
                                                Toast.makeText(
                                                        getActivity(),
                                                        "请检查手机是否联网！", Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        }
                                    })
                            .setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method
                                            // stub

                                        }
                                    }).show();

                }
            }
        });


        // Button btnshouye_zzcz = (Button) view.findViewById(R.id.btnshouye_zzcz);// 自助充值
        // btnshouye_zzcz.setOnClickListener(new OnClickListener() {

        //    @Override
        //     public void onClick(View v) {
        //       // TODO Auto-generated method stub
        //        if (!(App.getInstance().isLogin())) {
        //          Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
        //          gotoLoginView();
        //      } else {
        //         Intent intent = new Intent();
        //         intent.setClass(getActivity(), PayActivity.class);
        //         startActivity(intent);
        //      }
        // }
        //});

        Button sweep_zf = (Button) view.findViewById(R.id.sweep_zf);// 扫描支付
        sweep_zf.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), CaptureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivityForResult(intent, SCANNIN_GREQUEST_ONE);
                }
            }
        });
        Button sweep_km = (Button) view.findViewById(R.id.sweep_km);// 扫描开门
        sweep_km.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {

                    Intent intent = new Intent();
                    intent.setClass(getActivity(), CaptureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivityForResult(intent, SCANNIN_GREQUEST_TWO);

                }
            }
        });


        //
        Button btnupdatepass = (Button) view.findViewById(R.id.btnshouye_zzjg);// 收支分析
        btnupdatepass.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), AceActivity.class);
                    startActivity(intent);
                }
            }

        });
        Button leave = (Button) view.findViewById(R.id.leave); //请假
        leave.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), LeaveActivity.class);
                    startActivity(intent);
                }
            }
        });
        Button attendance = (Button) view.findViewById(R.id.attendance); //考勤
        attendance.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(App.getInstance().isLogin())) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    gotoLoginView();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), CaptureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivityForResult(intent, SCANNIN_GREQUEST_Three);
                }
            }
        });
        //

        // 等到屏幕的大小
        width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        // 以670*240的图片为例,正常中不要这样用
        height = width * 240 / 670;

        views = new ArrayList<View>();

        mParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        // vp = (ViewPager) view.findViewById(R.id.viewpager);

        viewFlow = (ViewFlow) view.findViewById(R.id.viewflow);
        showAd();

        return view;
    }

    private void gotoLoginView() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), LoginActivity.class);
        startActivityForResult(intent, 1000);
    }

    private void showActionbar() {
        SharedPreferences userInfo = getActivity().getSharedPreferences(
                "user_info", 0);
        boolean isLogin = userInfo.getBoolean("login", false);
        if (!isLogin) {
            btnloading.setText("登录");
            btnloading.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        } else {
            btnloading.setText("退出系统");
            btnloading.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_login_user, 0, 0, 0);
        }
    }

    /**
     * 接受消息,处理消息 ,此Handler会与当前主线程一块运行
     */

    class MyHandler extends Handler {
        public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法,接受数据
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.d("MyHandler", "handleMessage......");
            super.handleMessage(msg);
            // 此处可以更新UI
            switch (msg.arg1) {
                case 1:
                    if (Imageurl != null && !"".equals(Imageurl)
                            && logoimage != null) {
                        imageBetter.displayImage(Imageurl, logoimage);
                    }
                    if (urls != null && urls.length > 0) {
                        if (viewFlow != null) {
                            viewFlow.setAdapter(new ImageAdapter(getActivity(),
                                    urls, imagelist));
                            viewFlow.setmSideBuffer(pics.length); // 实际图片张数，
                            // 我的ImageAdapter实际图片张数为3

                            CircleFlowIndicator indic = (CircleFlowIndicator) view
                                    .findViewById(R.id.viewflowindic);
                            viewFlow.setFlowIndicator(indic);
                            viewFlow.setTimeSpan(2000);
                            viewFlow.setSelection(3 * 1000); // 设置初始位置
                            viewFlow.startAutoFlowTimer(); // 启动自动播放
                        }

                    }

                    break;
            }

        }
    }

    class ViewPagerAdapter extends PagerAdapter {

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView view = listviews.get(position);
            container.removeView(view);
            view.setImageBitmap(null);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int i) {
            if (i == 0) {
                listviews.get(i).setImageResource(pics[2]);
            } else if (i == (listviews.size() - 1)) {
                listviews.get(i).setImageResource(pics[0]);
            } else {
                listviews.get(i).setImageResource(pics[i - 1]);
            }
            container.addView(listviews.get(i));
            return listviews.get(i);
        }

        @Override
        public int getCount() {
            return listviews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }
    }

    /**
     * 设置当前的引导页
     */
    private void setCurView(int position) {
        if (position < 0 || position >= pics.length) {
            return;
        }

        vp.setCurrentItem(position);
    }

    /**
     * 这只当前引导小点的选中
     */
    private void setCurDot(int positon) {
        if (positon < 0 || positon > pics.length - 1 || currentIndex == positon) {
            return;
        }

        dots[positon].setEnabled(false);
        dots[currentIndex].setEnabled(true);

        currentIndex = positon;
    }

    // 当滑动状态改变时调用
    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    // 当当前页面被滑动时调用
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

        vp.requestDisallowInterceptTouchEvent(true);
    }

    // 当新的页面被选中时调用
    @Override
    public void onPageSelected(int i) {
        // 设置底部小点选中状态
        // setCurDot(i);
        int pageIndex = i;

        if (i == 0) {
            // 当视图在第一个时，将页面号设置为图片的最后一张。
            pageIndex = pics.length;
        } else if (i == pics.length + 1) {
            // 当视图在最后一个是,将页面号设置为图片的第一张。
            pageIndex = 1;
        }
        if (i != pageIndex) {
            vp.setCurrentItem(pageIndex, false);
            return;
        }
    }

    class SendHttpData implements Runnable {
        String url;
        String type;

        SendHttpData(String url, String type) {
            this.url = url;
            this.type = type;
        }

        @Override
        public void run() {
            SharedPreferences userInfo = getActivity().getSharedPreferences(
                    "user_info", 0);
            username = userInfo.getString("username", "");
            username = userInfo.getString("username", "");
            logintype = userInfo.getString("logintype", "");
            RequestParams requestparams = new RequestParams(url, "POST");
            requestparams.put("LoginAccount", username);
            requestparams.put("LoginType", logintype);
            requestparams.put("CardStatus", type);
            TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers,
                                      String responseString) {
                    // TODO Auto-generated method stub
                    Log.e("TAG", "responseString---" + responseString);
                    try {
                        AnalysisData(responseString);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      String responseString, Throwable throwable) {
                    // TODO Auto-generated method stub
                    Log.e("TAG", "responseString---" + responseString);

                }
            };
            try {
                new RestClient(getActivity()).post(url, requestparams,
                        textHttpResponseHandler);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         * json数据解析
         *
         * @param strResult
         * @throws JSONException
         */
        private void AnalysisData(String strResult) throws JSONException {
            /**
             * 这里需要分析服务器回传的json格式数据，
             */
            JSONObject jsonObject = new JSONObject(strResult);
            try {
                String returnMsg = jsonObject.getString("returnMsg");
                if (returnMsg == null || "".equals(returnMsg)) {
                    Toast.makeText(getActivity(), "成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), returnMsg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    class SendHttp implements Runnable {
        String url;
        String deCodeStr;
        String typ;

        SendHttp(String url, String deCodeStr, String typ) {
            this.url = url;
            this.deCodeStr = deCodeStr;
            this.typ = typ;
        }

        @Override
        public void run() {
            RequestParams requestparams = new RequestParams(url, "POST");
            requestparams.put("LoginAccount", username);
            requestparams.put("LoginType", logintype);//201402114
            requestparams.put("DeCodeStr", deCodeStr);
            TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers,
                                      String responseString) {
                    // TODO Auto-generated method stu
                    try {
                        Analysis(responseString);
                        Log.i("TAG", "responseString:" + responseString);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      String responseString, Throwable throwable) {
                    // TODO Auto-generated method stub
                    Log.i("TAG", "responseString---" + responseString);

                }
            };
            try {
                restClient.post(url, requestparams, textHttpResponseHandler);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         * json数据解析
         *
         * @param strResult
         * @throws JSONException
         */
        private void Analysis(String strResult) throws JSONException {
            /**
             * 这里需要分析服务器回传的json格式数据，
             */
            JSONObject jsonObject = new JSONObject(strResult);
            try {
                String returnMsg = jsonObject.getString("returnMsg");
                int leng = jsonObject.length();
                Log.i("TAG", "leng:" + leng);
                if (typ.equals("开门")) {
                    if (returnMsg == null || "".equals(returnMsg)) {
                        // TODO Auto-generated method stub
                        succes = "成功";
                    } else {
                        succes = "失败";
                    }

                } else {
                    if (leng != 1) {
                        String returnMsgSub = jsonObject.getString("returnMsgSub");
                        succes = returnMsg + returnMsgSub;
                    } else {
                        succes = returnMsg;
                    }

                }

                new AlertDialog.Builder(getActivity()).setTitle("系统提示")//设置对话框标题

                        .setMessage(typ + succes)//设置显示的内容

                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮

                            @Override

                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

                                // TODO Auto-generated method stub

                            }

                        }).show();//在按键响应事件中显示此对话框
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onClick(View view) {
        int position = (Integer) view.getTag();
        setCurView(position);
        setCurDot(position);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        getActivity().finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000) {
            showActionbar();

        }
        switch (requestCode) {
            case SCANNIN_GREQUEST_TWO:
                if (resultCode == getActivity().RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String typ = "开门";
                    //显示扫描到的内容
                    String result = bundle.getString("result");
                    boolean islianwang = new Constant()
                            .isConnect(getActivity());
                    if (islianwang) {
                        SendHttp sendhttp = new SendHttp(
                                App.getInstance().url
                                        + "/OpenDoolByScanCode",
                                result, typ);
                        sendhttp.run();
                    } else {
                        Toast.makeText(
                                getActivity(),
                                "请检查手机是否联网！", Toast.LENGTH_SHORT)
                                .show();
                    }

                }
                break;
            case SCANNIN_GREQUEST_ONE:
                if (resultCode == getActivity().RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    String result = bundle.getString("result");
                    if (result != null) {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), ScanPayActivity.class);
                        intent.putExtra("result", result);
                        startActivity(intent);
                    }

                }
                break;
            case SCANNIN_GREQUEST_Three:
                if (resultCode == getActivity().RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String typ = "考勤";
                    //显示扫描到的内容
                    String result = bundle.getString("result");
                    boolean islianwang = new Constant()
                            .isConnect(getActivity());
                    if (islianwang) {
                        SendHttp sendhttp = new SendHttp(
                                App.getInstance().url
                                        + "/AttByScanCode",
                                result, typ);
                        sendhttp.run();
                    } else {
                        Toast.makeText(
                                getActivity(),
                                "请检查手机是否联网！", Toast.LENGTH_SHORT)
                                .show();
                    }


                }

                break;
        }
    }
}
